package com.video.netty.commons.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;

@Component
public class NettySSLUtil {

    private volatile SSLContext sslContext = null;

    @Value("${golang.host}")
    private String golangHost;

    @Value("${golang.port}")
    private String golangPort;

    @Value("${golang.path}")
    private String golangPath;

    @Value("${server.ssl.enabled}")
    private boolean sslEnable;

    @Value("${server.ssl.key-store}")
    private String keyStore;

    @Value("${server.ssl.key-store-password}")
    private String keyPassword;

    @Value("${server.ssl.key-store-type}")
    private String keyType;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public SSLContext createSSLContext() throws Exception {
        if (null == sslContext) {
            synchronized (this) {
                if (null == sslContext) {
                    KeyStore ks = KeyStore.getInstance(keyType);

                    ClassPathResource resource = new ClassPathResource(keyStore.split(":")[1]);
                    InputStream ksInputStream = resource.getInputStream(); /// 证书存放地址
                    ks.load(ksInputStream, keyPassword.toCharArray());
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassword.toCharArray());
                    sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(kmf.getKeyManagers(), null, null);
                }
            }
        }
        return sslContext;
    }

    /**
     * 返回WebSocket服务器的url
     * @return
     */
    public String getWsPath(){
        //获取ip地址
        String redisGolangHost = redisTemplate.opsForValue().get("golangHost");
        if (redisGolangHost == null){
            redisGolangHost = golangHost;
        }

        //获取port地址
        String redisGolangPort = redisTemplate.opsForValue().get("golangPort");
        if (redisGolangPort == null){
            redisGolangPort = golangPort;
        }

        return (sslEnable ? "wss://" : "ws://") + redisGolangHost + ":" + redisGolangPort + golangPath;
    }
}
